package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.openai.models.evals.EvalCreateParams;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.DeviceShadowVo;
import com.zzyl.nursing.vo.ProductVo;
import okhttp3.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 智能设备表Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-01
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IoTDAClient client;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询智能设备表
     * 
     * @param id 智能设备表主键
     * @return 智能设备表
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询智能设备表列表
     * 
     * @param device 智能设备表
     * @return 智能设备表
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }


    @Override
    public void syncProductList() {
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        listProductsRequest.setLimit(50);
        ListProductsResponse response = client.listProducts(listProductsRequest);
        if(response.getHttpStatusCode()!= 200){
            throw new BaseException("同步失败");
        }
       // List<ProductSummary> products = response.getProducts();
        //保存到redis
        redisTemplate.opsForValue().set(CacheConstants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(response.getProducts()));
    }

    @Override
    public List<ProductVo> allProduct() {
        //查redid
        String product =(String) redisTemplate.opsForValue().get(CacheConstants.IOT_ALL_PRODUCT_LIST);

        return JSONUtil.toList(product, ProductVo.class);
    }

    /**
     * 注册设备
     * @param dto
     */
    @Override
    public void registerDevice(DeviceDto dto) {
        //设备名称是否重复
        long count = this.count(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()));
        if(count >0 ){
            throw new BaseException("设备名称重复");
        }
        //设备标识是否重复
       count = this.count(Wrappers.<Device>lambdaQuery().eq(Device::getNodeId, dto.getNodeId()));
        if(count >0 ){
            throw new BaseException("设备标识重复");
        }
        //同一位置是否绑定了相同的产品
        count = this.count(Wrappers.<Device>lambdaQuery()
                .eq(Device::getProductKey,dto.getProductKey())
                .eq(Device::getBindingLocation,dto.getBindingLocation())
                .eq(Device::getLocationType,dto.getLocationType())
                .eq(dto.getPhysicalLocationType() != null,Device::getPhysicalLocationType,dto.getPhysicalLocationType()));
        if(count >0){
            throw new BaseException("同一位置已绑定该产品");
        }
        //注册设备到IOT平台
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice boby = new AddDevice();
        boby.setProductId(dto.getProductKey());
        boby.setDeviceName(dto.getDeviceName());
        boby.setNodeId(dto.getNodeId());
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        AuthInfo info = new AuthInfo();
        info.withSecret(secret);
        boby.setAuthInfo(info);
        request.setBody(boby);
        AddDeviceResponse response = client.addDevice(request);
        if(response.getHttpStatusCode() != 201){
            throw new BaseException("注册失败");
        }
        //本地保存设备
        Device device = BeanUtil.toBean(dto, Device.class);
        device.setSecret(secret);
        device.setIotId(response.getDeviceId());
        this.save(device);
    }

    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //查询数据库
        Device device = this.getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (ObjectUtils.isEmpty(device)){
            throw new BaseException("设备不存在");
        }
        //查询华为云IOT
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse showDeviceResponse = client.showDevice(request);
        if(ObjectUtils.isEmpty(showDeviceResponse)){
            throw new BaseException("设备不存在");
        }

        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        deviceDetailVo.setBindingLocation(Long.valueOf(device.getBindingLocation()));
        deviceDetailVo.setDeviceStatus(showDeviceResponse.getStatus());
        if(!StringUtils.isEmpty(showDeviceResponse.getActiveTime())){
            LocalDateTime activeTime = LocalDateTimeUtil.parse(showDeviceResponse.getActiveTime(), DatePattern.UTC_MS_PATTERN);
            LocalDateTime time = DateTimeZoneConverter.utcToShanghai(activeTime);
            deviceDetailVo.setActiveTime(time);
        }

        return deviceDetailVo;
    }

    @Override
    public List<DeviceShadowVo> queryServiceProperties(String iotId) {
        //查询iot中设备的属性
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse showDeviceShadowResponse = client.showDeviceShadow(request);
        if(showDeviceShadowResponse.getHttpStatusCode() != 200){
            throw new BaseException("查询失败");
        }
        //获取上报数据集合
        List<DeviceShadowData> shadow = showDeviceShadowResponse.getShadow();
        //上报数据的属性
        DeviceShadowProperties reported = shadow.get(0).getReported();
        JSONObject jsonObject = JSONUtil.parseObj(reported.getProperties());

        List<DeviceShadowVo> list = new ArrayList<>();
        //获取上报事件时间
        String eventTime = reported.getEventTime();
        // 把字符串转换为LocalDateTime
        LocalDateTime eventTimeLocalDateTime = LocalDateTimeUtil.parse(eventTime, "yyyyMMdd'T'HHmmss'Z'");
        // 时区转换
        LocalDateTime eventTimer = DateTimeZoneConverter.utcToShanghai(eventTimeLocalDateTime);


        jsonObject.forEach((k,v) ->{
            DeviceShadowVo deviceShadowVo = new DeviceShadowVo();
            deviceShadowVo.setFunctionId(k);
            deviceShadowVo.setValue(v);
            deviceShadowVo.setEventTime(eventTimer);
            list.add(deviceShadowVo);
        });
        return list;
    }

    @Override
    @Transactional
    public void updateDevice(DeviceDto dto) {
        //修改数据库同时也要修改iot平台中的数据
        //修改数据库
        Device device = BeanUtil.toBean(dto, Device.class);
        boolean b = this.updateById(device);
        if(b==false){
            throw new BaseException("修改失败");
        }
        //修改iot
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        UpdateDevice body = new UpdateDevice();
        body.setDeviceName(dto.getDeviceName());
        body.setDescription(dto.getDeviceDescription());
        request.setBody(body);
        request.setDeviceId(dto.iotId);
        UpdateDeviceResponse sponse = client.updateDevice(request);
        if(sponse.getHttpStatusCode() != 200){
            throw new BaseException("IOT修改设备失败");
        }

    }

    @Override
    @Transactional
    public void deleteDevice(String iotId) {
        //删除数据库中的设备
        boolean remove = this.remove(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if(remove==false){
            throw  new BaseException("删除设备失败");
        }
        //删除iot平台中的设备
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(iotId);
        DeleteDeviceResponse sponse = client.deleteDevice(request);
        if(sponse.getHttpStatusCode() != 204){
            throw new BaseException("删除设备失败");
        }
    }

}
